package com.guozcc.bootweb.platform.common;

import org.apache.poi.util.IOUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class AutoHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final Map<String, String[]> parameterMap;
    private final byte[] bytes;

    public AutoHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        //初始化parameterMap
        this.parameterMap = new HashMap<>(request.getParameterMap());

        //初始化bytes
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        IOUtils.copy(request.getInputStream(),baos);
        this.bytes = baos.toByteArray();
    }


    @Override
    public Map<String, String[]> getParameterMap() {
        return parameterMap;
    }

    @Override
    public String[] getParameterValues(String name) {
        if(parameterMap==null){
            return super.getParameterValues(name);
        }else {
            String[] values = parameterMap.get(name);
            if(values == null){
                values = super.getParameterValues(name);
            }
            return values;
        }
    }
    public void setParameter(String key,String ...value){
        this.parameterMap.put(key,value);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return new ByteArrayInputStream(bytes).available()==0;
            }
            @Override
            public boolean isReady() {
                return true;
            }
            @Override
            public void setReadListener(ReadListener readListener) {}

            @Override
            public int read() throws IOException {
                return new ByteArrayInputStream(bytes).read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream(),getCharacterEncoding()==null?"UTF-8":getCharacterEncoding()));
    }


    public byte[] getBytes() {
        return bytes;
    }
}
